package com.security.config;

import com.security.exception.Oauth2ExceptionHandler;
import com.security.extractor.Oauth2BearerTokenExtractor;
import com.security.oauthfilter.Oauth2AccessDeniedExceptionFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.access.ExceptionTranslationFilter;

/**
 * Created by 陈圣融 on 2017-07-23.
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers().anyRequest().and()  //拦截url
                .authorizeRequests()
                .antMatchers("/favicon.ico", "/unoauthenticated", "/error").permitAll()
                .antMatchers("/api/**").access("#oauth2.hasScope('read')")  //配置权限
                .anyRequest().access("#oauth2.hasScope('readll')").and()
                .addFilterAfter(new Oauth2AccessDeniedExceptionFilter(), ExceptionTranslationFilter.class);
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                .authenticationEntryPoint(new Oauth2ExceptionHandler())
                .tokenExtractor(new Oauth2BearerTokenExtractor());
    }
    //    @Bean
//    public AccessDecisionManager accessDecisionManager(){
//        AccessDecisionManager accessDecisionManager=new AffirmativeBased();
//    }
//    @Bean
//    public AccessDeniedHandler accessDeniedHandler() {
//        AccessDeniedHandlerImpl accessDeniedHandler = new AccessDeniedHandlerImpl();
//        accessDeniedHandler.setErrorPage("/unauthenticated");
//        return accessDeniedHandler;
//    }
//
//    @Bean
//    public ExceptionTranslationFilter exceptionTranslationFilter() {
//        ExceptionTranslationFilter exceptionTranslationFilter = new ExceptionTranslationFilter(new OAuth2AuthenticationEntryPoint());
//        exceptionTranslationFilter.setAccessDeniedHandler(accessDeniedHandler());
//        return exceptionTranslationFilter;
//    }


}
